package com.lu.reggie.common;

import com.lu.reggie.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;

@Slf4j
//扫描加了这些注解的类
@RestControllerAdvice(annotations = {RestController.class, Controller.class})
public class GlobalExceputionHandler {


    /**
     * 目前仅仅是处理了员工添加重复错误
     * @param
     * @return
     */
    @ExceptionHandler({Exception.class})
    public R<String> exceptionHandler(Exception e) {
        if (e instanceof SQLIntegrityConstraintViolationException) {
            log.info(e.getMessage());
            if (e.getMessage().contains("Duplicate entry")) {
                String[] split = e.getMessage().split(" ");
                String msg = split[2] + "已存在!";
                return R.error(msg);
            }
        }
        if (e instanceof BusinessException) {
            log.info(e.getMessage());
            return R.error(e.getMessage());
        }
        return R.error("操作错误!");
    }
}
